package com.baoyouqun.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.RolePermissionCreateCmd;
import com.baoyouqun.domain.Query.RolePermissionQuery;
import com.baoyouqun.domain.UpdateCmd.RolePermissionUpdateCmd;
import com.baoyouqun.domain.VO.RolePermissionVO;
import com.baoyouqun.entity.RolePermission;
import com.baoyouqun.mapper.RolePermissionMapper;
import com.baoyouqun.service.RolePermissionService;
import com.baoyouqun.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Resource
    private RolePermissionMapper RolePermissionMapper;
    @Resource
    private RoleService roleService;


    @Override
    public boolean removeByRoleId(String roleId) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        return remove(queryWrapper);
    }

    @Override
    public SingleResponse<RolePermissionVO> create(RolePermissionCreateCmd cmd) {
        RolePermission entity =
                ConvertUtils.copyBean(cmd, RolePermission.class);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        RolePermissionVO vo =
                ConvertUtils.copyBean(entity, RolePermissionVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(RolePermissionUpdateCmd cmd) {
        // 1. 校验角色是否存在（需注入RoleService）
        if (roleService.getById(cmd.getRoleId()) == null) {
            return Response.buildFailure("100403", "角色不存在，无法修改权限");
        }

        // 2. 删除该角色原有的所有权限
        removeByRoleId(cmd.getRoleId());


        // 3. 绑定新权限（同创建角色的权限绑定逻辑）
        List<RolePermission> newRpList = cmd.getPermIdList().stream()
                .map(permId -> {
                    RolePermission rp = new RolePermission();
                    rp.setId("RP" + IdUtil.simpleUUID().replaceAll("-", ""));
                    rp.setRoleId(cmd.getRoleId());
                    rp.setPermId(permId);
                    return rp;
                })
                .collect(Collectors.toList());

        boolean saveNew = saveBatch(newRpList);
        return saveNew ? Response.buildSuccess() : Response.buildFailure("100405", "绑定新权限失败");
    }

    @Override
    public RolePermissionVO selectById(String id) {
        RolePermission entity = baseMapper.selectById(id);
        RolePermissionVO vo =
                ConvertUtils.copyBean(entity, RolePermissionVO.class);
        return vo;
    }


    @Override
    public IPage<RolePermissionVO> pageVo(RolePermissionQuery query) {
        IPage<RolePermission> page = new Page<RolePermission>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<RolePermission>());
        Page<RolePermissionVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        page.getRecords().forEach(entity -> {
            RolePermissionVO vo =
                    ConvertUtils.copyBean(entity, RolePermissionVO.class);
            voPage.getRecords().add(vo);
        });
        return voPage;
    }

    @Override
    public List<String> selectPermissionIdsByRoleIds(List<String> roleIds) {
        if (roleIds == null || roleIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<RolePermission> list = list(new LambdaQueryWrapper<RolePermission>().in(RolePermission::getRoleId, roleIds));
        return list.stream().filter(Objects::nonNull).map(RolePermission::getPermId).collect(Collectors.toList());

    }
}